const Web3 = require('web3');
const BigNumber = require('bignumber.js');
const retry = require('bluebird-retry');
const retryPromise = require('bluebird');

const erc20Abi = require('./abi/ERC20.json');
const config = require('../config');

function ERC20(chain, contractAddress, privateKey) {
    let self = this;
    self.web3 = new Web3(chain.rpc);
    self.chain = chain;
    self.contractAddress = contractAddress;
    self.tokenContract = new self.web3.eth.Contract(erc20Abi, contractAddress);
    if (!privateKey.startsWith('0x')) {
        privateKey = '0x' + privateKey;
    }
    let account = self.web3.eth.accounts.privateKeyToAccount(privateKey);
    self.web3.eth.accounts.wallet.add(account);
    self.web3.eth.defaultAccount = account.address;
}



ERC20.prototype.balanceOf = async function (address) {
    let self = this;
    return new Promise((resolve, reject) => {
        retry(() => {
            return self.tokenContract.methods.balanceOf(address).call();
        }, { max_tries: 5, interval: 3000 }).then(function (result) {
            resolve(result);
        }).catch(function (error) {
            reject(error);
        });
    });
}

ERC20.prototype.transfer = async function (toAddress, amount) {
    let self = this;
    let options = {
        from: self.web3.eth.defaultAccount,
        gas: self.chain.gasLimit,
        gasPrice: self.chain.gasPrice,
        value: 0
    }
    return new Promise((resolve, reject) => {
        retry(() => {
            return self.tokenContract.methods.transfer(toAddress, amount).send(options);
        }, { max_tries: 5, interval: 3000 }).then(function (result) {
            resolve(result);
        }).catch(function (error) {
            reject(error);
        });
    });
}

module.exports = ERC20;